package apiwork.lcbmi.util.config;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.log4j.Logger;
import org.dom4j.Attribute;
import org.dom4j.Element;

import com.linkage.util.config.MemoryConfig;
import com.linkage.util.config.SystemConfig;
import com.linkage.util.xml.XMLProperties;

public class DataMappingConfig extends MemoryConfig{
	private Logger log=Logger.getLogger(DataMappingConfig.class);
	private static DataMappingConfig m_instance = null;
	private static XMLProperties xmlProperties = null;
	
	private DataMappingConfig(){}
	
	public static DataMappingConfig getInstance() {
		if (m_instance == null) {
			m_instance = new DataMappingConfig();
		}
		return m_instance;
	}
	
	synchronized public void reload() throws Exception {
		try{
			if(isReload() || xmlProperties == null){
				String xmlFile = SystemConfig.getInstance().getConfig("DataMapping");
				xmlProperties = new XMLProperties(xmlFile);
			}
			setReload(false);
		}catch(Exception e){
			throw new Exception(e);
		}
	}
	
	@SuppressWarnings("unchecked")
	public void getObjectDataMapInfo(String objType, HashMap objsInfoMap,String objName) {
		log.info("---objtype="+objType+",objName="+objName+",objsInfoMap="+objsInfoMap);
		HashMap objAttrsMap = new HashMap();
		ArrayList<HashMap<String, String>> objPropsList = new ArrayList<HashMap<String, String>>();
		Element objEle;
		try {
			reload();
			objAttrsMap.put("name", objName);
			objEle = xmlProperties.getElement("data.operation_obj."
					+ objType);
			log.info("objEle="+objEle);
			List<Attribute> objAttrs = (List<Attribute>) objEle.attributes();
			log.info("objAttrs="+objAttrs);
			for (Attribute attr : objAttrs) {
				objAttrsMap.put(attr.getName(), attr.getValue());
			}
			ArrayList<Element> objSubEles = (ArrayList<Element>) objEle
					.elements();
			for (Element objSubEle : objSubEles) {
				HashMap<String, String> objPropAttrsMap = new HashMap<String, String>();
				List<Attribute> objPorpAttrs = (List<Attribute>) objSubEle
						.attributes();
				objPropAttrsMap.put("propname", objSubEle.getName());
				for (Attribute propAttr : objPorpAttrs) {
					objPropAttrsMap
							.put(propAttr.getName(), propAttr.getValue());
				}				
				objPropsList.add(objPropAttrsMap);
//				log.info("objPropAttrsMap=="+objPropAttrsMap);
//				
//				
//				for (Attribute propAttr : objPorpAttrs) {
//					objPropAttrsMap
//							.put(propAttr.get, propAttr.getValue());
//				}
				
			}
			objAttrsMap.put("propslist", objPropsList);
			objsInfoMap.put(objName, objAttrsMap);
			
		} catch (Exception e) {
		}
	}
	
	
	public String getProperties(String name) throws Exception{
		try{
			reload();
			return xmlProperties.getElementValue(name);
		}catch(Exception e){
			e.printStackTrace();
			return "";
		}
    }
}
